package com.bjsxt.net.tcp3;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 客户端
 * @author Administrator
 *
 */
public class LoginClient {

    public static void main(String[] args) {
        //声明socket套接字
        Socket client = null;

        boolean flag ;

        try {
            //创建socket套接字
            client = new Socket("127.0.0.1",7788);

            //创建输入流，用于接收用户输入
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            //用于向服务器端发送数据
            ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
            //用于接收服务器端反馈数据
            DataInputStream dis = new DataInputStream(client.getInputStream());

            while(true){
                System.out.print("请输入用户名：");
                String username = br.readLine();
                System.out.print("请输入密码：");
                String password = br.readLine();

                //封装数据，准备向服务器端发送
                User user = new User(username, password);

                //发送
                oos.writeObject(user);

                //接收服务器端反馈
                flag = dis.readBoolean();
                if(flag){
                    System.out.println(username + "登录成功！");
                    break;
                }else{
                    System.out.println("登录失败，请重新登录：");
                }
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
